package cn.com.haopy.yue.ai.admin.web;

import cn.com.haopy.yue.ai.admin.annotation.RequiresPermissionsDesc;
import cn.com.haopy.yue.ai.core.utils.ResponseUtil;
import cn.com.haopy.yue.ai.core.validator.Order;
import cn.com.haopy.yue.ai.core.validator.Sort;
import cn.com.haopy.yue.ai.db.entity.arisk.AIRiskTopic;
import cn.com.haopy.yue.ai.db.entity.arisk.AIRiskTopicOptions;
import cn.com.haopy.yue.ai.db.entity.arisk.HOSAdmin;
import cn.com.haopy.yue.ai.db.service.hos.AIRiskTopicOptionsService;
import cn.com.haopy.yue.ai.db.service.hos.AIRiskTopicService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @Description: TODO
 * @Author DuTao
 * @Date 2025/3/26 9:21
 */
@RestController
@RequestMapping("/admin/risk/topic")
@RequiredArgsConstructor
@Slf4j
@Api(tags = "AI题目相关")
public class AdminAiRiskTopicController {
    @Autowired
    private AIRiskTopicService riskTopicService;

    @Autowired
    private AIRiskTopicOptionsService riskTopicOptionsService;

    @RequiresPermissions("admin:risk:topic:list")
    @RequiresPermissionsDesc(menu = {"信息维护", "AI题目管理"}, button = "AI题目查询")
    @GetMapping("/list")
    @ApiOperation("列表")
    public Object list(@RequestParam(required = false) @ApiParam("AI题目") String topic,
                       @RequestParam(required = false) @ApiParam("是否有效") Integer isActive,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "create_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        Page<AIRiskTopic> riskTopicList = riskTopicService.querySelective(topic, isActive, page, limit, sort, order);
        return ResponseUtil.okPage(riskTopicList);
    }

    @RequiresPermissions("admin:risk:topic:create")
    @RequiresPermissionsDesc(menu = {"信息维护", "AI题目管理"}, button = "AI题目添加")
    @PostMapping("/create")
    @ApiOperation("新增")
    @Transactional
    public Object create(@RequestBody AIRiskTopic riskTopic) {
        Object error = validate(riskTopic);
        if (error != null) {
            return error;
        }
        Subject currentUser = SecurityUtils.getSubject();
        HOSAdmin admin = (HOSAdmin) currentUser.getPrincipal();
        riskTopic.setCreateBy(admin.getUsername());
        riskTopic.setUpdateBy(admin.getUsername());
        List<AIRiskTopic> riskTopicList = riskTopicService.getByTopic(riskTopic.getTopic());
        if (!CollectionUtils.isEmpty(riskTopicList)) {
            return ResponseUtil.fail("题目已经存在");
        }
        boolean isSuccess = riskTopicService.save(riskTopic);
        if (!isSuccess) {
            return ResponseUtil.fail("添加失败");
        }
        return ResponseUtil.ok("添加成功");
    }

    @RequiresPermissions("admin:risk:topic:update")
    @RequiresPermissionsDesc(menu = {"信息维护", "AI题目管理"}, button = "AI题目修改")
    @PostMapping("/update")
    @ApiOperation("编辑")
    @Transactional
    public Object update(@RequestBody AIRiskTopic riskTopic) {
        AIRiskTopic riskTopicEntity = riskTopicService.getById(riskTopic.getId());
        if (Objects.isNull(riskTopicEntity)) {
            return ResponseUtil.fail("题目信息不存在");
        }

        // 题目唯一性校验
        if (!Objects.equals(riskTopic.getTopic(), riskTopicEntity.getTopic())) {
            List<AIRiskTopic> riskTopicList = riskTopicService.getByTopic(riskTopic.getTopic());
            if (!CollectionUtils.isEmpty(riskTopicList)) {
                return ResponseUtil.fail("AI题目已经存在！");
            }
        }
        Subject currentUser = SecurityUtils.getSubject();
        HOSAdmin admin = (HOSAdmin) currentUser.getPrincipal();
        riskTopic.setUpdateBy(admin.getUsername());
        if (riskTopicService.updateById(riskTopic)) {
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @RequiresPermissions("admin:risk:topic:delete")
    @RequiresPermissionsDesc(menu = {"信息维护", "AI题目管理"}, button = "AI题目删除")
    @GetMapping("/delete")
    @ApiOperation("删除")
    @Transactional
    public Object delete(@RequestParam Integer id) {
        if (riskTopicService.removeById(id)) {
            // 在删除题目时候，对应的所有答案也要全部删除
            List<AIRiskTopicOptions> riskTopicOptionsList = riskTopicOptionsService.getByTopicId(id);
            if (riskTopicOptionsList.size() <= 0) {
                return ResponseUtil.ok("删除成功");
            } else if (riskTopicOptionsService.deleteByTopicId(id) > 0) {
                return ResponseUtil.ok("删除成功");
            }
        }
        return ResponseUtil.fail("删除数据失败");
    }

    private Object validate(AIRiskTopic data) {
        if (!StringUtils.hasText(data.getTopic())) {
            return ResponseUtil.badArgumentValue();
        }
        return null;
    }
}
